package com.wxtf.platform.main.employee;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.xml.registry.infomodel.User;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.wxtf.platform.interfaces.CommonsCallProvider;
import com.wxtf.platform.plugins.user.UserBean;
import com.wxtf.platform.supers.LogicBase;
import com.wxtf.platform.tools.ConstantInfoHelper;
import com.wxtf.platform.tools.AccessDataBaseUtil;
import com.wxtf.platform.tools.FormatUtil;

/**
 * <li>Title: EmpTemporary.java</li>
 * <li>Project: baseplatform</li>
 * <li>Package: com.wxtf.platform.main.employee</li>
 * <li>Description: </li>
 * <li>Copyright: Copyright (c) 2012</li>
 * <li>Company: wxthtf Technologies </li>
 * <li>Created on Aug 21, 2012 10:29:02 AM</li>
 * 
 * @author zhanqiulin
 * @version 1.0.0.0
 * 
 */
public class EmpTemporary extends LogicBase implements CommonsCallProvider{
	private static final Log log = LogFactory.getLog(EmpTemporary.class);

	public EmpTemporary(String jsonArray){
 
	}
	
	@Override
	public Object run() {
		Object msg = "";
		try {
			if("queryPage".equals(this.getMethodName())) {
				msg = this.select(this.getLogicData());
			} else if("save".equals(this.getMethodName())) {
				msg = this.insert(this.getLogicData());
			} else if("update".equals(this.getMethodName())) {
				msg = this.update(this.getLogicData());
			} else if("queryAll".equals(this.getMethodName())) {
				msg = this.queryAll(this.getLogicData());
			} else {
				msg = "\"没有【" + this.getMethodName() + "】该方法\"";
			}

			if(msg == null || "[null]".equals(msg)) {
				msg = "\"\"";
			}
			if(msg.toString().startsWith("{") || msg.toString().startsWith("[")){
				return msg;
			}
			msg = ConstantInfoHelper.generateJSONString(msg.toString());
		} catch(Exception e) {
			msg = ConstantInfoHelper.generateErrorJSONString();
			log.error(e, e);
		} finally {
			this.clear();
		}
		return msg.toString();
	}

	private	List<String> sqlList;
	@Override
	public Object select(Object jsonArray) throws Exception {
		UserBean user = (UserBean)this.getRequest().getSession().getAttribute("userBean");
		JSONArray array = JSONArray.fromObject(jsonArray);
		String orgId = "";
		if(array.size() > 0) {
			JSONObject jsonObject = JSONObject.fromObject(array.getString(0));
			orgId = jsonObject.getString("orgId");//机构ID串
		}
		if(StringUtils.isBlank(orgId)){
			orgId = user.getCurOrgId();
		}
		String querySql = "select tbt_id,org_id,tbt_num,tbt_time,reserve1,reserve2,reserve3,reserve4,reserve5,create_by,create_time,last_modify_by,last_modify_time from tb_temporary where org_id = '"+user.getCurOrgId()+"' ";
	 	List<Object[]> list = AccessDataBaseUtil.query(querySql, null);
	 	JSONObject json = new JSONObject();
	 	if(list.size() > 0){
	 		Object[] o = list.get(0);
	 		json.put("orgId", o[1]);
	 		json.put("num", o[2]);
	 		return "["+json.toString()+"]";
	 	}
 	 	return "[]";
	}
	public Object queryAll(Object jsonArray) throws Exception {
		UserBean user = (UserBean)this.getRequest().getSession().getAttribute("userBean");
		JSONArray array = JSONArray.fromObject(jsonArray);
		String orgId = "";
		if(array.size() > 0) {
			JSONObject jsonObject = JSONObject.fromObject(array.getString(0));
			orgId = jsonObject.getString("orgId");//机构ID串
		}
		if(StringUtils.isBlank(orgId)){
			orgId = user.getCurOrgId();
		}
		String sql2 = "select b.tbt_id,a.department_id,a.caption,b.tbt_num from (select department_id,caption,ordernum from t_department where department_id = ?)  a left join tb_temporary b on a.department_id = b.org_id order by a.ordernum";
		List<Map<String,Object>> list =  AccessDataBaseUtil.query4ListMap(fields, sql2, new Object[] { orgId });
		list = this.getOrgByPid(list);
		JSONArray jsonArr = JSONArray.fromObject(list);
		String msg = "{\"Rows\":"+jsonArr.toString()+"}";
		return msg;
	}

	private String[] fields = { "tbt_id", "org_id", "name", "num"};
	private String sql = "select b.tbt_id,a.department_id,a.caption,b.tbt_num from (select department_id,caption,ordernum from t_department where dparent_id = ?)  a left join tb_temporary b on a.department_id = b.org_id order by a.ordernum";
	private List<Map<String,Object>> getOrgByPid(List<Map<String,Object>> list) throws Exception{
		if(null == list || list.size() <= 0){
			return null;
		}
		for(Map<String,Object> map: list){
			String org_id = String.valueOf(map.get("org_id"));
			List<Map<String,Object>> list1 = AccessDataBaseUtil.query4ListMap(fields, sql, new Object[] { org_id });
			map.put("children", list1);
			this.getOrgByPid(list1);
		}
		return list;
	}
	@Override
	public Object insert(Object jsonArray) throws Exception {
		UserBean user = (UserBean)this.getRequest().getSession().getAttribute("userBean");
		sqlList = new ArrayList<String>();
		JSONArray array = JSONArray.fromObject(jsonArray);
		String orgId = "";
		int num = 0;
		if(array.size() > 0) {
			JSONObject jsonObject = JSONObject.fromObject(array.getString(0));
			orgId = jsonObject.getString("orgId");//
			num = jsonObject.getInt("num");
		}
		if(StringUtils.isBlank(orgId)){
			orgId = user.getCurOrgId();
		}
		List<Object[]> list = select1(orgId);
		String curTime = FormatUtil.getCurentDateTime();
		int n = num;
		if(list.size() == 0){
			sqlList.add(insert1(orgId, num, user, curTime));
		}else{
			Object[] o = list.get(0);
			n = num - Integer.parseInt(o[2].toString());
			sqlList.add(update1(o[0].toString(), num, user, curTime));
		}
		String pid = user.getOrgPId(orgId);
		if(StringUtils.isNotBlank(pid)){
			changeTempCount(pid, n, user, curTime);
		}
		AccessDataBaseUtil.executeSQLUpdate(sqlList);
		return "\"保存成功\"";
	}
	public void changeTempCount(String orgId,int num,UserBean user,String curTime) throws Exception {
		List<Object[]> list = select1(orgId);
		if(list.size() == 0){
			sqlList.add(insert1(orgId, num, user, curTime));
		}else{
			Object[] o = list.get(0);
			int n = num + Integer.parseInt(o[2].toString());
			sqlList.add(update1(o[0].toString(), n, user, curTime));
		}
		String pid = user.getOrgPId(orgId);
		if(StringUtils.isNotBlank(pid)){
			changeTempCount(pid, num, user, curTime);
		}
	}

	public List<Object[]> select1(String orgId) throws Exception {
		String querySql = "select tbt_id,org_id,tbt_num,tbt_time,reserve1,reserve2,reserve3,reserve4,reserve5,create_by,create_time,last_modify_by,last_modify_time from tb_temporary where org_id = '"+orgId+"' ";
		return AccessDataBaseUtil.query(querySql, null);
	}
	public String insert1(String orgId,int num,UserBean user,String curTime) throws Exception {
		StringBuffer buf = new StringBuffer();
		buf.append("insert into tb_temporary (tbt_id,org_id,tbt_num,tbt_time,reserve1,reserve2,reserve3,reserve4,reserve5,create_by,create_time,last_modify_by,last_modify_time)") 
		.append(" values('").append(AccessDataBaseUtil.getPKUUID()).append("','").append(orgId)
			.append("','").append(num).append("','','','','','','','")
			.append(user.getUserId()).append("','").append(curTime).append("','").append(user.getUserId()).append("','")
			.append(curTime).append("')");
		return buf.toString();
	}
	public String update1(String id,int num,UserBean user,String curTime) throws Exception {
		StringBuffer buf = new StringBuffer();
		buf.append("update tb_temporary set tbt_num='").append(num).append("',last_modify_by='").append(user.getUserId()).append("',last_modify_time='").append(curTime).append("'") 
		.append(" where tbt_id='").append(id).append("'");
		return buf.toString();
	}

	@Override
	public Object update(Object jsonArray) throws Exception {
		return "\"修改成功\"";
	}

	@Override
	public Object delete(Object jsonArray) throws Exception {
		
		
		return "\"删除成功\"";
	}

	@Override
	public Object recordCount(Object jsonArray) throws Exception {
		return null;
	}

	@Override
	public Object setRequest(HttpServletRequest request) throws Exception {
		this.request = request;
		return request;
	}

	@Override
	public Object updateBatch(Object jsonArray) throws Exception {
		return null;
	}

	@Override
	public Object onCreate(Object jsonArray) {
		return null;
	}

	@Override
	public Object onDestory(Object jsonArray) {
		return null;
	}

	@Override
	public Object onInit(Object jsonArray) {
		return null;
	}
	
	
}


